from fastapi import APIRouter, Depends, File, Form, UploadFile
from fastapi.security import OAuth2PasswordRequestForm
from typing import List, Optional
from . import models, service, auth

router = APIRouter()


# 认证相关路由
@router.post("/register", response_model=models.Response)
async def register(
    email: str = Form(...),
    password: str = Form(...),
    nickname: str = Form(...),
    avatar: Optional[UploadFile] = File(None),
):
    # 处理头像文件上传
    avatar_url = await utils.save_upload_file(avatar)
    user = models.UserCreate(email=email, password=password, nickname=nickname, avatar=avatar_url)
    db_user = service.register_user(user)
    return {"success": True, "record": db_user}


@router.post("/login", response_model=models.Response)
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    user = service.authenticate_user(form_data.username, form_data.password)
    if not user:
        return {"success": False, "message": "Incorrect email or password"}
    token = auth.create_access_token({"sub": user.id})
    return {"success": True, "record": token}


# 用户相关路由
@router.get("/user/profile", response_model=models.Response)
async def get_user_profile(
    current_user: models.TokenData = Depends(auth.get_current_user),
):
    user = service.get_user_profile(current_user.user_id)
    return {"success": True, "record": user}


# 标签相关路由
@router.get("/user/tag", response_model=models.Response)
async def get_user_tags(
    skip: int = 0,
    limit: int = 100,
    current_user: models.TokenData = Depends(auth.get_current_user),
):
    tags = service.get_user_tags(current_user.user_id, skip=skip, limit=limit)
    return {
        "success": True,
        "query": {
            "page": skip // limit + 1,
            "limit": limit,
            "count": len(tags),
            "results": tags,
        },
    }


@router.post("/user/tag", response_model=models.Response)
async def create_tag(
    tag: models.TagCreate,
    current_user: models.TokenData = Depends(auth.get_current_user),
):
    db_tag = service.create_tag(tag, current_user.user_id)
    return {"success": True, "record": db_tag}


# 提示词相关路由
@router.get("/prompt", response_model=models.Response)
async def get_prompts(skip: int = 0, limit: int = 100, keyword: Optional[str] = None):
    prompts = service.get_prompts(skip=skip, limit=limit, keyword=keyword)
    return {
        "success": True,
        "query": {
            "page": skip // limit + 1,
            "limit": limit,
            "count": len(prompts),
            "results": prompts,
        },
    }


@router.get("/prompt/{prompt_id}", response_model=models.Response)
async def get_prompt(prompt_id: int):
    prompt = service.get_prompt(prompt_id)
    return {"success": True, "record": prompt}


@router.post("/prompt/{prompt_id}/like", response_model=models.Response)
async def like_prompt(prompt_id: int):
    prompt = service.like_prompt(prompt_id)
    return {"success": True, "record": prompt}


@router.get("/user/prompt", response_model=models.Response)
async def get_user_prompts(
    skip: int = 0,
    limit: int = 100,
    current_user: models.TokenData = Depends(auth.get_current_user),
):
    user = service.get_user_profile(current_user.user_id)
    prompts = service.get_prompts(skip=skip, limit=limit, user_id=user.id)
    return {
        "success": True,
        "query": {
            "page": skip // limit + 1,
            "limit": limit,
            "count": len(prompts),
            "results": prompts,
        },
    }


@router.post("/user/prompt", response_model=models.Response)
async def create_prompt(
    prompt: models.PromptCreate,
    current_user: models.TokenData = Depends(auth.get_current_user),
):
    db_prompt = service.create_prompt(prompt, current_user.user_id)
    return {"success": True, "record": db_prompt}


# 收藏相关路由
@router.get("/user/collection", response_model=models.Response)
async def get_user_collections(
    skip: int = 0,
    limit: int = 100,
    current_user: models.TokenData = Depends(auth.get_current_user),
):
    collections = service.get_user_collections(
        current_user.user_id, skip=skip, limit=limit
    )
    return {
        "success": True,
        "query": {
            "page": skip // limit + 1,
            "limit": limit,
            "count": len(collections),
            "results": collections,
        },
    }


@router.post("/user/collect/{prompt_id}", response_model=models.Response)
async def collect_prompt(
    prompt_id: int, current_user: models.TokenData = Depends(auth.get_current_user)
):
    collection = service.create_collection(current_user.user_id, prompt_id)
    return {"success": True, "record": collection}


@router.delete("/user/collect/{prompt_id}", response_model=models.Response)
async def uncollect_prompt(
    prompt_id: int, current_user: models.TokenData = Depends(auth.get_current_user)
):
    return service.delete_collection(current_user.user_id, prompt_id)
